using System;
using System.Web;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Util;
using newtelligence.DasBlog.Web.Core;
using newtelligence.DasBlog.Web.Services.Rss20;
using System.Xml;
using System.Xml.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace newtelligence.DasBlog.Web.Services
{
    public partial class WebWebServices
	{

        [OperationContract, XmlSerializerFormat, WebGet(UriTemplate="/timeline")]
        public timeline TimelineHandler( )
        {
            try
            {
				//Cache the sitemap for 8 hours...
				string CacheKey = "TimelineXml";
				timeline root = System.Web.Hosting.HostingEnvironment.Cache[CacheKey] as timeline ;
				if (root == null) //we'll have to build it...
				{
					root = new timeline();
					root.events = new eventCollection();

					int i = 0;

					//All Pages (stop after 750...it gets too big and the browser can't handle it...we'd need
					// to include dynamic paging
                    EntryCollection entryCache = dataService.GetAllEntries(true); 
                    foreach(Entry e in entryCache)
                    {
                        if (e.IsPublic && (++i < 750))
                        {
                            //then add permalinks
                            string url = Utils.GetPermaLinkUrl(siteConfig,e);
                            @event foo = new @event(e.CreatedLocalTime, false, TruncateDotDotDot(StripAllTags(e.Title),50),url);
                            foo.text += String.Format("<div align=\"right\"><a href=\"{0}\">More...</a></div>",url);
                            root.events.Add(foo);
                        }
                    }
				
					System.Web.Hosting.HostingEnvironment.Cache.Insert(CacheKey,root,null,DateTime.Now.AddHours(8),System.Web.Caching.Cache.NoSlidingExpiration);
				}

                return root;
			}
            catch(Exception exc)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,exc);
                return null;
            }
        }

		private string TruncateDotDotDot(string content, int maxlen)
		{
			string retVal = StripAllTags(content); //Important to strip tags FIRST or we could truncate in the middle of a TAG, rather than in the middle of content.
			if (retVal.Length > maxlen)
				retVal = retVal.Substring(0, Math.Min(maxlen, retVal.Length)) + "...";
			return retVal;
		}
		
		private string StripAllTags(string content)
		{
			string regex = "<(.|\n)+?>";
			System.Text.RegularExpressions.RegexOptions options = System.Text.RegularExpressions.RegexOptions.IgnoreCase;
			System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);
			string retVal = content;
			try
			{
				retVal = reg.Replace(content, String.Empty);
			}
			catch
			{ //swallow anything that might go wrong
			}
			return retVal;
		}
        
	}
}
